package com.xiaodaidai.bllogsystem.service.impl;

import com.github.pagehelper.PageHelper;
import com.xiaodaidai.bllogsystem.mapper.ArticleMapper;
import com.xiaodaidai.bllogsystem.mapper.CommentMapper;
import com.xiaodaidai.bllogsystem.mapper.StatisticMapper;
import com.xiaodaidai.bllogsystem.po.Article;
import com.xiaodaidai.bllogsystem.po.Comment;
import com.xiaodaidai.bllogsystem.po.StaticticsBo;
import com.xiaodaidai.bllogsystem.po.Statistic;
import com.xiaodaidai.bllogsystem.service.ISiteService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
/**
 * ISiteService接口实现类
 * @Date 2021-3-14 13:14
 * @Created by XiaoDaiDai
 */
@Service
@Transactional
public class SiteServiceImpl implements ISiteService {
    @Resource
    private CommentMapper commentMapper;
    @Resource
    private ArticleMapper articleMapper;
    @Resource
    private StatisticMapper statisticMapper;
    // 最新收到的评论
    public List<Comment> recentComments(int limit) {
        PageHelper.startPage(1,limit>10 || limit<1 ? 10:limit);
        List<Comment> commentList = commentMapper.selectNewComment();
        return commentList;
    }

    // 最新发表的文章
    public List<Article> recentArticles(int limit) {
        PageHelper.startPage(1,limit>10 || limit<1 ? 10:limit);
        List<Article> articleList = articleMapper.selectArticleWithPage();
        //封装文章统计数据
        for(int i = 0;i < articleList.size();i++){
            Article article = articleList.get(i);
            Statistic statistic = statisticMapper.selectStatisticWithArticleId(article.getId());
            article.setHits(statistic.getHits());
            article.setCommentsNum(statistic.getCommentsNum());
        }
        return articleList;
    }

    // 获取后台统计数据
    public StaticticsBo getStatistics() {
        StaticticsBo staticticsBo = new StaticticsBo();
        Integer articles = articleMapper.countArticle();
        Integer comments = commentMapper.countComment();
        staticticsBo.setArticles(articles);
        staticticsBo.setComments(comments);
        return staticticsBo;
    }

    // 更新某个文章的统计数据
    public void updateStatistics(Article article) {
        Statistic statistic = statisticMapper.selectStatisticWithArticleId(article.getId());
        statistic.setHits(statistic.getHits()+1);
        statisticMapper.updateArticleHitsWithId(statistic);
    }
}
